package com.tju.backend.resources.config.security.components;

import com.tju.backend.entity.SysBackendApi;
import com.tju.backend.resources.config.security.custom.MyaccessDeniedException;
import com.tju.backend.service.business.SysBackendApiService;
import com.tju.backend.utils.tool.EmptyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


/**
 * 动态权限
 *
 * @USER: CLS
 */
@Component
public class DynamicPermission {

    @Autowired
    SysBackendApiService backendApiService;


    /**
     * 判断有访问API的权限
     *
     * @param request
     * @param authentication
     * @return
     * @throws MyaccessDeniedException
     */
    public boolean checkPermisstion(HttpServletRequest request,
                                    Authentication authentication) throws MyaccessDeniedException {
        Object principal = authentication.getPrincipal();

        if (principal instanceof UserDetails) {
            UserDetails userDetails = (UserDetails) principal;
            //得到当前的账号
            String username = userDetails.getUsername();

            //通过账号获取资源鉴权
            List<SysBackendApi> apiUrls = backendApiService.getApiUrlByUserName(username);

            //当前访问路径
            String requestURI = request.getRequestURI();
            //提交类型
            String urlMethod = request.getMethod();
            if (EmptyUtils.isNotEmpty(requestURI) && EmptyUtils.isNotEmpty(urlMethod)) {
                //判断当前路径中是否在资源鉴权中
                if (whetherAuthentication(apiUrls, requestURI, urlMethod)) {
                    return true;
                } else
                    throw new MyaccessDeniedException("您没有访问该API的权限！");
            } else
                throw new MyaccessDeniedException("不是UserDetails类型！");
        } else
            throw new MyaccessDeniedException("不是UserDetails类型！");
    }

    /**
     * TODO：判断当前api和请求发送是否在资源鉴权中
     *
     * @param apiUrls
     * @param requestURI
     * @param urlMethod
     * @return
     */
    private boolean whetherAuthentication(List<SysBackendApi> apiUrls, String requestURI, String urlMethod) {
        boolean hashAntPath = false;
        int hasMethod = 0;
        for (SysBackendApi apiUrl : apiUrls) {
            if (EmptyUtils.isNotEmpty(apiUrl)) {
                //判断请求方式是否和数据库中匹配（数据库存储：GET,POST,PUT,DELETE）
                if (apiUrl.getUrl().equals(requestURI) && apiUrl.getMethod().equals(urlMethod)) {
                    String dbMethod = apiUrl.getMethod();
                    //处理null，万一数据库存值
                    dbMethod = (dbMethod == null) ? "" : dbMethod;
                    hasMethod = dbMethod.indexOf(urlMethod);
                    hashAntPath = true;
                }
            }
        }
        //两者都成立，返回真，否则返回假
        return hashAntPath && (hasMethod != -1);
    }
}

























